package com.zrrd.gmall.product.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zrrd.gmall.common.result.Result;
import com.zrrd.gmall.model.product.SkuInfo;
import com.zrrd.gmall.product.service.SkuInfoService;
import com.zrrd.gmall.rabbit.constant.MqConstant;
import com.zrrd.gmall.rabbit.service.RabbitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/admin/product")
public class SkuInfoController {

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private RabbitService rabbitService;

    //分页查询Sku列表
    @GetMapping("/list/{page}/{limit}")
    public Result<Page> list(@PathVariable("page") Integer page,
                             @PathVariable("limit") Integer size){
        //创建分页对象
        Page<SkuInfo> pageInfo = new Page<>(page,size);
        //执行分页查询
        skuInfoService.page(pageInfo,null);
        //返回结果
        return Result.ok(pageInfo);
    }

    //sku上架
    @GetMapping("/onSale/{skuId}")
    public Result<String> onSale(@PathVariable("skuId") Long skuId){
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(1);
        //更新
        boolean update = skuInfoService.updateById(skuInfo);
        if (update){
            //发送MQ消息
            rabbitService.sendMessage(MqConstant.EXCHANGE_DIRECT_GOODS,MqConstant.ROUTING_GOODS_UPPER,skuId);
        }
        //返回
        return Result.ok("成功");
    }

    //sku下架
    @GetMapping("/cancelSale/{skuId}")
    public Result<String> cancelSale(@PathVariable("skuId") Long skuId){
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(0);
        //更新
        boolean update = skuInfoService.updateById(skuInfo);
        if (update){
            //发送MQ消息
            rabbitService.sendMessage(MqConstant.EXCHANGE_DIRECT_GOODS,MqConstant.ROUTING_GOODS_LOWER,skuId);
        }
        //返回
        return Result.ok("成功");
    }

    //根据SpuId获取Spu图片列表->添加Sku支持
    @GetMapping("/spuImageList/{spuId}")
    public Result<List> spuImageList(@PathVariable("spuId") Long spuId){
        return Result.ok(skuInfoService.getSpuImageList(spuId));
    }

    //根据SpuId获取Spu销售属性以及关联的属性值列表 ->添加Sku支持
    @GetMapping("/spuSaleAttrList/{spuId}")
    public Result<List> spuSaleAttrList(@PathVariable("spuId") Long spuId){
        return Result.ok(skuInfoService.getSpuSaleAttrList(spuId));
    }

    //添加Sku
    @PostMapping("/saveSkuInfo")
    public Result<String> saveSkuInfo(@RequestBody SkuInfo skuInfo){
        skuInfoService.saveSkuInfo(skuInfo);
        return Result.ok("成功");
    }
}
